package com.systemframework.util;


import cn.hutool.core.codec.Base64;
import com.systemframework.constants.Constants;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author summer
 * @date 2022-10-21 9:42
 */
public class Base64ToMultipartFile implements MultipartFile {

    private final byte[] imgContent;
    private final String header;

    private final String MARKS_=";";

    private final String SLASH="/";

    public Base64ToMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(MARKS_)[0];

    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + Math.random() + Constants.FILE_STATE_ID + header.split(SLASH)[1];
    }


    @Override
    public String getOriginalFilename() {
        return System.currentTimeMillis() + (int)Math.random() * 10000 + Constants.FILE_STATE_ID + header.split(SLASH)[1];
    }

    @Override
    public String getContentType() {
        return header.split(Constants.COLON_)[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes()  {
        return imgContent;
    }

    @Override
    public InputStream getInputStream()  {
        return new ByteArrayInputStream(imgContent);
    }


    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imgContent);
    }


    public static MultipartFile base64ToMultipart(String base64) {
        String[] base = base64.split(Constants.COMMA);
        byte[] decode = Base64.decode(base[1]);
        return new Base64ToMultipartFile(decode, base[0]);
    }



}
